package com.ericzong.util.file.xml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jUtils
{
    
	/**
	 * 保存 xml 文档
	 * 
	 * @param document
	 *            要保存的 Document 对象
	 * @param fileName
	 *            文件路径
	 * @throws IOException
	 */
	public static void save(Document document, String fileName) throws IOException
	{
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setExpandEmptyElements(true);
		// format.setSuppressDeclaration(true);
		// format.setOmitEncoding(true);
		format.setNewLineAfterDeclaration(false);
		format.setLineSeparator("\r\n");
		XMLWriter writer = new XMLWriter(format);
		writer.setOutputStream(new FileOutputStream(fileName));
		writer.write(document);
	}

	public static Document read(String fileName) throws FileNotFoundException, DocumentException
	{
		SAXReader reader = new SAXReader();
		Document document = reader.read(new FileInputStream(fileName));
		return document;
	}
}
